<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 *
 * @author Julot.
 * @since Friday, February 11, 2011.
 */
class UserIdentity extends CUserIdentity {

	/**
	 * @var integer user id in database.
	 */
	private $_id;

	/**
	 * @property integer $id the user id in database.
	 */
	public function getId() {
		return $this->_id;
	}

	/**
	 * Authenticates a user.
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate() {
		$s = 'LOWER(username) = ?';
		$user = User::model()->find($s, array(strtolower($this->username)));
		if ($user === null) $this->errorCode = self::ERROR_USERNAME_INVALID;
		else if (!$user->validatePassword($this->password)) {
			$this->errorCode = self::ERROR_PASSWORD_INVALID;
		} else {
			$this->_id = $user->_id;
			$this->username = $user->username;
			$this->errorCode = self::ERROR_NONE;
			$this->setState('memberId', $user->memberId ? $user->memberId : 0);
		}
		return $this->errorCode == self::ERROR_NONE;
	}

}